const express = require('express');
const router = express.Router();


function bookRouteModule(db) {

    //得到图书列表  可传参数，当前页码，当前展示数量  默认为1，10
    router.get('/list', async (req, res) => {
        const page = parseInt(req.query.page) || 1;
        const size = parseInt(req.query.size) || 10;

        const offset = (page - 1) * size;

        try {
            const [totalResult] = await db.query('SELECT COUNT(*) as total FROM book');

            // 得到当前图书列表里的总数
            const total = totalResult[0].total;

            const [rows] = await db.query('SELECT * FROM book LIMIT ?,?', [offset, size]);

            res.json({
                code: 200,
                message: "ok",
                data: {
                    count: total,
                    list: rows
                }
            })

            console.log(totalResult, "totalResult");

        } catch (error) {
            console.log(error, "错误");
            res.status(500).send({ code: 500, msg: '服务器错误,请稍后重试' });
        }
    })

    //添加图书
    router.post('/add', async (req, res) => {
        const { BookID, Title, Author, ISBN, Publisher, PublishDate, Category, Stock } = req.body;
        const query = 'INSERT INTO books (BookID, Title, Author, ISBN, Publisher, PublishDate, Category, Stock) VALUES (?, ?, ?, ?, ?, ?, ?, ?)';
        const values = [BookID, Title, Author, ISBN, Publisher, PublishDate, Category, Stock];
        try {
            const [result] = await db.query(query, values); // 返回插入的行数
            console.log(result, "result");
            res.json({
                code:200,
                message:"图书添加成功！"
            })
        } catch (error) {
            console.log(error, "错误");
            res.status(500).send({ code: 500, msg: '图书添加失败,请稍后重试' });
            
        }
    })


    return router;
}

module.exports = bookRouteModule;